#include "spi.h"

/*************************************************************************
函 数 名：SPI_Configuration
函数功能：初始spi,用于sd卡数据
*************************************************************************/
void SPI_Configuration(void)
{
	GPIO_InitTypeDef GPIO_InitStructure;

	// SD GPIO Periph clock enable
	RCC_AHB1PeriphClockCmd(SD_CS_RCC|SD_MOSI_RCC|SD_MISO_RCC|SD_SCK_RCC, ENABLE);
	// SD_SPI Periph clock enable
	RCC_APB1PeriphClockCmd(SD_SPI_RCC, ENABLE);

	GPIO_PinAFConfig(SD_SCK_GPIO, SD_SCK_SOURCE, SD_SCK_AF);
	GPIO_PinAFConfig(SD_MISO_GPIO, SD_MISO_SOURCE, SD_MISO_AF);
	GPIO_PinAFConfig(SD_MOSI_GPIO, SD_MOSI_SOURCE, SD_MOSI_AF);

	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
	GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
	GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	
	// Configure SD_SPI pins: SCK
	GPIO_InitStructure.GPIO_Pin = SD_SCK_PIN;
	GPIO_Init(SD_SCK_GPIO, &GPIO_InitStructure);

	// Configure SD_SPI pins: MOSI/DI
	GPIO_InitStructure.GPIO_Pin = SD_MOSI_PIN;
	GPIO_Init(SD_MOSI_GPIO, &GPIO_InitStructure);

	// Configure SD_SPI pins: MISO/DO
	GPIO_InitStructure.GPIO_Pin = SD_MISO_PIN;
	GPIO_Init(SD_MISO_GPIO, &GPIO_InitStructure);

	// Configure SD_SPI pins: CS
	GPIO_InitStructure.GPIO_Pin = SD_CS_PIN;
	GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
	GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
	GPIO_Init(SD_CS_GPIO, &GPIO_InitStructure);
    

	SPI_InitTypeDef   SPI_InitStructure;

	// SD_SPI Config
	SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;
	SPI_InitStructure.SPI_Mode = SPI_Mode_Master;
	SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;
	SPI_InitStructure.SPI_CPOL = SPI_CPOL_High;
	SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge;
	SPI_InitStructure.SPI_NSS = SPI_NSS_Soft;
	SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_256;
	SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;
	SPI_InitStructure.SPI_CRCPolynomial = 7;
	SPI_Init(SD_SPI, &SPI_InitStructure);

	// SD_SPI enable
	SPI_Cmd(SD_SPI, ENABLE);
}